package frameWork.mainComponent;


import frameWork.entity.Node;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;


/**
 * 任务分配者，Node为最小任务
 */
public class MainAssigner{
    private Thread[] ThreadChi=new Thread[16];
    private BlockingDeque<Node> blockingDeque =new LinkedBlockingDeque<>();
    Tick tick=new Tick();

    public int getQueueSize(){
        return blockingDeque.size();
    }

    public boolean isAllFinish(){
        return tick.isZero();
    }

    public void addNode(Node node){
        try{
            blockingDeque.put(node);
        }catch(InterruptedException e){
            //e.printStackTrace();
        }
    }

    public MainAssigner(){
        for(int i=0;i<ThreadChi.length;i++){
            ThreadChi[i]=new Thread(() -> {
                try{
                    for(;;){
                            Node node=blockingDeque.take();
                            tick.add();
                            node.run();
                            tick.remove();
                    }
                }catch(InterruptedException e){
                    //e.printStackTrace();
                }
            });
            ThreadChi[i].start();
        }
    }
}

class Tick{
    int sum=0;
    public synchronized void add(){
        sum++;
    }
    public synchronized void remove(){
        sum--;
    }
    public synchronized boolean isZero(){
        return sum==0;
    }
}
